#coding=utf-8
import time,datetime,os
import stutils

import datetime
today = datetime.date.today()
endyear = today.year
endmonth = today.month
def get_jd(month):
    return (month-1)/3 + 1
endjd = get_jd(endmonth)

price_head = ["日期", "开盘价",	"最高价", "收盘价", "最低价","交易量(手)", "交易金额(万元)"]

def get_price_from_soup(soup):

    def get_s(item):
        while True:
            r = item.string
            if r: return r.strip()
            item = item.contents[0]
            
    def get_data_from_row(row):

        r = []
        tds = row.findAll('td')

        for td in tds:
            r.append(get_s(td))
        print r
        if not r[0] :
            td0 = tds[0]
            rq = td0.contents[0].contents[1].string.strip()
            r[0] = rq
        
        return r

    r = []
    
    t = unicode('日期', 'u8')
    rq = soup.find(text = t)
    
    if not rq:return None
    
    table = rq.parent.parent.parent.parent.parent
    trs = table.findAll('tr')[2:]

    for tr in trs:
        d = get_data_from_row(tr)
        r.append(d)

    r.reverse()
    #unicode 2 u8
    for i in range(len(r)):
        for j in range(len(price_head)):
            r[i][j] = r[i][j].encode('u8')
    return r

def get_histprice_by_jd(code, year, jd):

    url = 'http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml?year=%s&jidu=%s'%(code, year, jd)
    s = stutils.get_soup(url)
    data = get_price_from_soup(s)
    
    return data
    
def get_yjs(sy, sjd, ey, ejd):
    #jd 代表季度
    #eg: get_yjs(2005,2) ==> [[]]
    #注意:all params are integer
    
    l = []
    if sy == ey:
        for jd in range(sjd, ejd+1):
            l.append([sy, jd])
        return l
        
    for jd in range(sjd, 5):
        l.append( [sy, jd] )
        
    years = range(sy+1, ey)    
    for y in years:
        for jd in range(1, 5):
            l.append( [y, jd] )
    
    for jd in range(1, ejd+1):
        l.append( [ey, jd] )
    
    l = [[str(i[0]), str(i[1])] for i in l]
    return l

class NoPriceError(Exception):
    def __init__(self, code, exdate):
        self.code = code
        self.date = exdate
        
    def __str__(self):
        return "%s: no Price Data on %s"%(self.code, self.date)
    
def get_todayprice(code):
    '''获取当天的price'''
    td = datetime.date.today().isoformat()
    url = 'http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml'%code
    s = stutils.get_soup(url)
    data = get_price_from_soup(s) 
    if not data:
        print "no data in this 季度"
        raise NoPriceError(code, td)
            
    data = data[-1]
    if data[0] != td:
        raise NoPriceError(code, td)
    
    return data

def get_price_on(code, exdate):
    '''取得某一股票某一天的价格'''
    from stvalidator import isValidExDate
    isValidExDate(exdate)
    
    year, month, day = map(int, exdate.split('-'))
    jd = get_jd(month)
    data = get_histprice_by_jd(code, year, jd)
    
    for d in data:
        if d[0] == exdate:
            return d
    
    raise NoPriceError(code, exdate)

def get_price_since(code, exdate, ey=endyear , ejd=endjd):
    '''取得某一股票从某一天开始至今的价格'''
    year, month, day = map(int, exdate.split('-'))
    
    sy = year
    sjd = get_jd( month)
    #print sy,sjd
    yjs = get_yjs(sy,sjd,ey,ejd)
    
    data = []
    for yj in yjs:
        d = get_histprice_by_jd(code, *yj)
        if not d:
            continue
        data.extend(d)
        
    if not data:
        print "%s: no data since %s"%(code, exdate)
        return None 
    
    dates = [d[0] for d in data]
    index = 0
    for i in range(len(dates)):
        if dates[i] >= exdate:
            index = i
            break
                    
    return data[i:]

if __name__ == '__main__':
    from stsettings import datadir
    ipofn = datadir + '/ipo.csv'
    
    cis = stutils.csv2data(ipofn)
    for ci in cis:
        code, ipo = ci
        fn = '%s/histprice/%s.csv'%(datadir,code)
        if os.path.exists(fn):continue
        
        ipo = datetime.date(*map(int, ipo.split('-')))
        data = get_histprice(code, ipo)
        
        stutils.data2csv(data, price_head, fn)
        
        print code
        time.sleep(0.5)
